//
//  CJSettingViewController.m
//  CoJellyCartoon
//
//  Created by dllo on 16/4/8.
//  Copyright © 2016年 CJG. All rights reserved.
//

#import "CJSettingViewController.h"
#import "CJCollectionViewController.h"
#import "CJDownloadViewController.h"
@interface CJSettingViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) CJBaseTableView *SettingTableView;

@property (nonatomic, strong) NSMutableArray *arrayAll;

@property (nonatomic,strong) NSMutableArray *arrayImage;

@property (nonatomic, strong) UILabel *labelClear;

@end

@implementation CJSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.arrayAll = [NSMutableArray arrayWithObjects:@"离线缓存", @"清理缓存", @"夜间模式", @"我的收藏", nil];
    self.arrayImage = [NSMutableArray arrayWithObjects:@"L10.png",@"L11.png",@"L12.png",@"L14.png", nil];
    
    [self creatTableView];
    
    
}

-(void)creatTableView{

    self.SettingTableView = [[CJBaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, SCREEN_HEIGHT) style:UITableViewStylePlain];

    self.SettingTableView.delegate = self;
    self.SettingTableView.dataSource = self;
    
    [self.view addSubview:self.SettingTableView];
    
    [self.SettingTableView registerClass:[CJBaseTableViewCell class] forCellReuseIdentifier:@"reuse"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayAll.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CJBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    cell.textLabel.text = _arrayAll[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:self.arrayImage[indexPath.row]];
    
    
    if (indexPath.row == 1) {
      //清除缓存:
        self.labelClear = [[UILabel alloc]initWithFrame:CGRectMake(150, 20, 120, 20)];
        self.labelClear.text = [NSString stringWithFormat:@"已缓存%.2fM",[self filePath]];
        [cell addSubview:self.labelClear];
    }
    if (indexPath.row == 2){
        //夜间模式
        UISwitch *switchB = [[UISwitch alloc]initWithFrame:CGRectMake(0.5 * SCREEN_WIDTH, 0.02 * SCREEN_HEIGHT, 0.16 * SCREEN_WIDTH, 0.015 * SCREEN_HEIGHT)];
        [cell addSubview:switchB];
        
        
        //设置状态
        
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"NightMode"] isEqualToString:@"Night"]) {//说明开关是开的(夜间模式)
            [switchB setOn:YES];
        }else{
            [switchB setOn:NO];//(日间模式)
        }
        [switchB addTarget:self action:@selector(NightModeB:) forControlEvents:UIControlEventValueChanged];
    }
    
    
    

    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    

//    [self.myDeleGate pushText];
    
    
    if (indexPath.row == 3) {
        CJCollectionViewController *collectVC = [[CJCollectionViewController alloc] init];
        [self.navigationController pushViewController:collectVC animated:YES];
    }

    if (indexPath.row == 1) {
        //清理缓存
        [self clearCash];
    }
    
    if (indexPath.row == 0) {
        CJDownloadViewController *downloadVC = [[CJDownloadViewController alloc] init];
        [self.navigationController pushViewController:downloadVC animated:YES];
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}

///夜间模式
- (void)NightModeB:(UISwitch *)btn{
    
    //(@",,,cc");
    
    if (btn.isOn == YES) {
        //说明是夜间状态
        [[NSUserDefaults standardUserDefaults] setObject:@"Night" forKey:@"NightMode"];
        //(@"夜间");
    }else{
        //说明是白天
        [[NSUserDefaults standardUserDefaults] setObject:@"Day" forKey:@"NightMode"];
        //(@"白天");
    }
    
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeColor" object:nil];
    
    
    
}


// 显示缓存大小

- ( float )filePath

{
  
    //需要清除文件内存的大小(获取文件路径)
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

//2: 遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）

- ( float ) folderSizeAtPath:( NSString *) folderPath{

    
    //文件管理者
    NSFileManager *manger = [NSFileManager defaultManager];
    
    //判断是否存在文件cash
    if (![manger fileExistsAtPath:folderPath]) {
        return 0;
    }
    NSEnumerator *childFilesEnumerator = [[manger subpathsAtPath:folderPath ] objectEnumerator];
    
    NSString *fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil)  {
        
        NSString *fileAvsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAvsolutePath];
        
    }
    
    return folderSize / (1024.0 * 1024.0);
    
}

-(long long)fileSizeAtPath:(NSString *)filePath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if ([manager fileExistsAtPath :filePath]){
        
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
        
    }
    
    return 0 ;
    
    
}

///清除缓存
- (void)clearCash{
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"是否清除缓存:%.2fM",[self filePath]] preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alert animated:YES completion:^{
        
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            //先找文件路径
            NSString  *cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask ,  YES )  objectAtIndex : 0 ];
            
            ///通过文件管理者找出子路径
            NSArray *files = [[ NSFileManager defaultManager ]  subpathsAtPath :cachPath];
            
            // ( @"files :%ld" ,(unsigned long)[files  count]);
            
            ///遍历这个数组
            
            for ( NSString *p  in files) {
                
                NSError *error;
                
                NSString *path = [cachPath  stringByAppendingPathComponent :p];
                
                if ([[ NSFileManager defaultManager ]  fileExistsAtPath :path]) {
                    
                    //删除文件
                    [[ NSFileManager defaultManager ]  removeItemAtPath :path  error :&error];
                    
                }
                
            }
            
            //在主线程上执行
            [ self performSelectorOnMainThread : @selector (clearCacheSuccess)  withObject : nil waitUntilDone : YES ];
            
            
        });
        
        
    }];
    
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [alert addAction:cancle];
    [alert addAction:action];
    
    
    
}

- (void)clearCacheSuccess{
    
    self.labelClear.text =
    [NSString stringWithFormat:@"%.2fM",[self filePath]];
}

@end
